//
//  ViewController.m
//  RAC
//
//  Created by 宜必鑫科技 on 2017/10/25.
//  Copyright © 2017年 宜必鑫科技. All rights reserved.

//  filter  通过的条件  map 转换为另外一个对象值。
//  flattenMap 将信号中的信号传递给下一个

#import "ViewController.h"
#import "MusicNetTool.h"
#import "BaseKnowledgeController.h"
#import "OneViewController.h"
#import "TwoViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextField *passtextField;
@property (nonatomic, strong) UIButton *signBut;
@property (nonatomic, strong) UIButton *baseKnowledge;
@property (nonatomic, strong) UIButton *oneBut;
@property (nonatomic, strong) UIButton *twoBut;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //既可以让计算位置从导航栏下面开始 又可以让导航栏透明
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, ScreenWidth - 20, 50)];
    _textField.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_textField];
    
    _passtextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 110, ScreenWidth - 20, 50)];
    _passtextField.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_passtextField];
    
    _signBut = [[UIButton alloc]initWithFrame:CGRectMake(10, 170, ScreenWidth - 20, 50)];
    _signBut.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_signBut];
    
    _baseKnowledge = [[UIButton alloc]initWithFrame:CGRectMake(10, 230, ScreenWidth - 20, 50)];
    [_baseKnowledge setTitle:@"基础知识" forState:UIControlStateNormal];
    _baseKnowledge.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_baseKnowledge];
    [[_baseKnowledge rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        BaseKnowledgeController *view = [[BaseKnowledgeController alloc]init];
        [self.navigationController pushViewController:view animated:YES];
    }];
    
    _oneBut = [[UIButton alloc]initWithFrame:CGRectMake(10, 290, ScreenWidth - 20, 50)];
    _oneBut.backgroundColor = [UIColor lightGrayColor];
    [_oneBut setTitle:@"后往前传值" forState:UIControlStateNormal];
    [self.view addSubview:_oneBut];
//    [_oneBut addTarget:self action:@selector(OnClickOne) forControlEvents:1<<6];
    [[_oneBut rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        OneViewController *vc = [[OneViewController alloc]init];
        [self presentViewController:vc animated:YES completion:nil];
        [vc.delegateSubject subscribeNext:^(id  _Nullable x) {
            WJLogError(@"OneViewController %@",x);
        }];
    }];
    _twoBut = [[UIButton alloc]initWithFrame:CGRectMake(10, 350, ScreenWidth - 20, 50)];
    _twoBut.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_twoBut];
    [[_twoBut rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
    }];
    

    /**
     Signal 发送事件 subscribe接受事件
     目前总共有三种类型的事件：next、error、completed。
     一个signal在因error终止或者完成前，可以发送任意数量的next事件。
     */
    [_textField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
       // WJLogWarn(@"%@",x);
    }];
    
    
    /**
     rac_textSignal是起始事件。然后数据通过一个filter，如果这个事件包含一个长度超过3的字符串，那么该事件就可以通过。
     filter操作的输出也是RACSignal
     */
    [[_textField.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        NSString *str = value;
        return str.length > 3;
    }]subscribeNext:^(NSString * _Nullable x) {
         //WJLogError(@"%@",x);
    }];
    
    
    /**
     map从上一个next事件接收数据，通过执行block把返回值传给下一个next事件。
     在上面的代码中，map以NSString为输入，取字符串的长度，返回一个NSNumber。
     */
    [[[_textField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        return @(value.length);
    }]filter:^BOOL(NSNumber *value) {
        return [value integerValue] > 3;
    }]subscribeNext:^(id  _Nullable x) {
        //WJLogError(@"%@",x);
    }];
    
    
    /**
      map 的使用 改变颜色
     */
    RACSignal *racsignalmap = [_textField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        return @([self isValidUsername:value]);
    }];
    RAC(_textField, backgroundColor) = [racsignalmap map:^id _Nullable(NSNumber *value) {
        return [value boolValue]?[UIColor yellowColor]:[UIColor redColor];
    }];
    
    
    
    /**
      聚合信号
     */
    RACSignal *racsignal = [_textField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        return @([self isValidUsername:value]);
    }];
    RACSignal *passRacsignal = [_passtextField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        return @([self isValidUsername:value]);
    }];
    RACSignal *signal = [RACSignal combineLatest:@[racsignal,passRacsignal] reduce:^id (NSNumber*usernameValid, NSNumber *passwordValid){
        return @([usernameValid boolValue] &&[passwordValid boolValue]);
    }];
    
    [signal subscribeNext:^(NSNumber *x) {
        _signBut.backgroundColor = [x boolValue]?[UIColor yellowColor]:[UIColor redColor];;
    }];
    
   
    /**
      创建信号  与将信号发送给下面
     */
    [[[[_signBut rac_signalForControlEvents:UIControlEventTouchUpInside]doNext:^(__kindof UIControl * _Nullable x) {
        _signBut.enabled = false;
        _signBut.alpha = 0.4;
    }] flattenMap:^__kindof RACSignal * _Nullable(__kindof UIControl * _Nullable value) {
        return [self loginStatus];
    }] subscribeNext:^(id  _Nullable x) {
        _signBut.enabled = true;
        _signBut.alpha = 1;
        NSLog(@"Sign in result: %@", x);
    } error:^(NSError * _Nullable error) {
        WJLogError(@"Sign in error: %@", error);
    }];
    
}


- (RACSignal *)loginStatus
{
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [MusicNetTool getMusicDataWithPageId:1 completionHandle:^(id resuposeObject, NSError *error) {
            if (error) {
                [subscriber sendError:error];
            }else{
                [subscriber sendNext:resuposeObject];
                [subscriber sendCompleted];
            }
        }];
        return nil;
    }];
}


- (BOOL)isValidUsername:(NSString *)str
{
    if (str.length % 2 == 0) {
        return YES;
    }
    return NO;
}


/**
 问题1：navigationController 会收不到信息
 */
- (void)OnClickOne
{
    OneViewController *vc = [[OneViewController alloc]init];
    [self presentViewController:vc animated:YES completion:nil];
    [vc.delegateSubject subscribeNext:^(id  _Nullable x) {
        WJLogError(@"OneViewController %@",x);
    }];
}
@end
